<template>
  <div class="ai-layout">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'AILayout',
  data() {
    return {
      userId: localStorage.getItem('loginId') || '',
      isLoggedIn: false
    }
  },
  created() {
    this.checkLoginStatus()
    const existingWs = this.$store.state.webSocket
    if (!existingWs || existingWs.readyState === WebSocket.CLOSED) {
      this.connectWebSocket()
    }
  },
  methods: {
    checkLoginStatus() {
      this.isLoggedIn = !!localStorage.getItem('loginId')
      return this.isLoggedIn
    },
    connectWebSocket() {
      if (!this.checkLoginStatus()) {
        this.$message.error('未登录，请先登录')
        return
      }

      const existingWs = this.$store.state.webSocket
      if (existingWs && existingWs.readyState === WebSocket.OPEN) {
        return
      }
      
      const ws = new WebSocket(`ws://localhost:4003/socket/subject/${this.userId}`)
      
      ws.onopen = () => {
        console.log('WebSocket连接已建立')
        this.$store.commit('setWebSocket', ws)
      }
      
      ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.reconnectWebSocket()
      }

      ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        if (this.$route.name.includes('AI')) {
          this.$store.commit('setWebSocket', null)
          this.reconnectWebSocket()
        }
      }
    },

    reconnectWebSocket() {
      const maxRetries = 5
      const retryInterval = 3000
      let retryCount = 0

      const retry = () => {
        if (!this.checkLoginStatus()) {
          this.$message.error('可能未登录，无法连接服务器')
          return
        }

        if (retryCount < maxRetries) {
          console.log(`尝试重新连接... (${retryCount + 1}/${maxRetries})`)
          setTimeout(() => {
            this.connectWebSocket()
            if (!this.$store.state.webSocket || this.$store.state.webSocket.readyState !== WebSocket.OPEN) {
              retryCount++
              retry()
            }
          }, retryInterval)
        } else if (retryCount === maxRetries) {
          this.$message.error('可能未登录，无法连接服务器')
          retryCount++
        }
      }

      retry()
    },

    // 提供一个方法供子组件调用来检查登录状态
    checkLoginBeforeAction() {
      if (!this.checkLoginStatus()) {
        this.$message.error('请先登录后再操作')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>
.ai-layout {
  height: 100vh;
  width: 100%;
}
</style> 